package org.dhbw.jee.web.beans;

import java.io.Serializable;
import java.text.MessageFormat;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.*;

public class AbstractController implements Serializable {
	private static final long serialVersionUID = 1L;

	public FacesContext getContext() {
		return FacesContext.getCurrentInstance();
	}

	public <T> T evaluateEL(String elExpression, Class<T> beanClass) {
		return getContext().getApplication().evaluateExpressionGet(getContext(), elExpression, beanClass);
	}

	public String postMessageAndRefreshPage(String mlsKey, Object... mlsParams) {
		getContext().addMessage(null, new FacesMessage(getMlsMessage(mlsKey, mlsParams)));
		return getContext().getViewRoot().getViewId();
	}

	public String getMlsMessage(String key, Object... params) {
		String message = getContext().getApplication().getResourceBundle(getContext(), "mls").getString(key);
		if (params != null && params.length > 0) {
			return MessageFormat.format(message, params);
		} else {
			return message;
		}
	}

	// ** REQUEST ****************************************************************************** //

	public HttpServletRequest getHttpRequest() {
		return (HttpServletRequest) getContext().getExternalContext().getRequest();
	}

	public Object getHttpRequestEntry(String key) {
		return getContext().getExternalContext().getRequestMap().get(key);
	}

	@SuppressWarnings("unchecked")
	public <T> T getHttpRequestEntry(String key, Class<T> entryClass) {
		return (T) getHttpRequestEntry(key);
	}

	// ** SESSION ****************************************************************************** //

	public HttpSession getHttpSession() {
		return getHttpSession(true);
	}

	public HttpSession getHttpSession(boolean shouldCreate) {
		return (HttpSession) getContext().getExternalContext().getSession(shouldCreate);
	}

	public Object getHttpSessionEntry(String key) {
		return getContext().getExternalContext().getSessionMap().get(key);
	}

	@SuppressWarnings("unchecked")
	public <T> T getHttpSessionEntry(String key, Class<T> entryClass) {
		return (T) getHttpSessionEntry(key);
	}

}
